var http = require("http");
const Router = require("./router");

var app = (module.exports = function (req, res) {
  console.log("start");
  app.handle(req, res);
});

app.handle = function (req, res) {
  const finalHandle = () => {
    res.end(` cantnot  ${req.method} ${req.url}`);
  };
  this.router.handle(req, res, finalHandle);
};

app.lazyrouter = function (params) {
  if (!this.router) {
    this.router = new Router();
  }
};

app.route = function (path) {
  this.lazyrouter();

  const route = this.router.route(path);

  return route;
};

app.get = function (path, ...args) {
  this.lazyrouter();

  const route = this.router.route(path);
  console.log(this === app);
  route.get(...args);

  return this;
};

app.listen = function (...args) {
  let sever = http.createServer(app);

  sever.listen(...args);
};

app.param = function (name, callback) {
  this.lazyrouter();

  if (Array.isArray(name)) {
    name.forEach((n) => this.param(n, callback));
    return this;
  }
  this.router.param(name, callback);
  return this;
};

app.use = function (fn) {
  let offset = 0;
  path = "/";
  if (typeof fn !== "function") {
    path = fn;
    offset = 1;
  }

  const callbacks = [].slice.call(arguments, offset);

  this.lazyrouter();

  callbacks.forEach((callback) => this.router.use(path, callback));
  return this;
};
